﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Reflection;
using System.Text.RegularExpressions;

namespace DataSystem
{
    public interface IDataProvider
    {
        void SetConnection(string connectionsString);

        List<Dictionary<string, object>> GetData(string sql);

        List<Dictionary<string, object>> GetData(string connectionsString, string sql);

        

    }

    public static class IDataProvidersExtensions
    {

        public static List<Dictionary<string, object>> InvokeTextFunction(this IDataProvider pro, string function)
        {
            // use regular expression to get function name and paramters as strings
            string txt = function;
            string funcationname = "";
            List<string> parameters = new List<string>();

            string re1 = "((?:[a-z][a-z]+))";	// Word 1
            string re2 = "(\\(.*\\))";	// Round Braces 1

            Regex r = new Regex(re1 + re2, RegexOptions.IgnoreCase | RegexOptions.Singleline);
            Match m = r.Match(txt);
            if (m.Success)
            {
                funcationname = m.Groups[1].ToString();
                foreach (var param in m.Groups[2].ToString().TrimStart('(').TrimEnd(')').Split(','))
                {
                    parameters.Add(param.Trim());
                }

            }

            MethodInfo methodinf = null;

            foreach (var method in pro.GetType().GetMethods())
            {
                if (method.Name.ToLower() == funcationname && method.GetParameters().Count() == parameters.Count) methodinf = method;
            }

            List<object> parametersArr = new List<object>();
            //int i = 0;
            //foreach (var p in methodinf.GetParameters())
            //{
            //    string parameterobject = Activator.CreateInstance(p.ParameterType, parameters[i] );

            //    parametersArr.Add(parameterobject);
            //    i++;
            //} 
            try
            {
                 return (List<Dictionary<string, object>>)methodinf.Invoke(pro, parameters.ToArray());
            }
            catch { return null; }


        }


    }


}
